import os
import subprocess
import sys
import tempfile


def run_ffmpeg(cmd, desc=None, silent=True):
    """执行 ffmpeg 命令，并打印描述"""
    if desc:
        print(f"▶ {desc}")
    try:
        if silent:
            subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
        else:
            subprocess.run(cmd, check=True)
        return True
    except subprocess.CalledProcessError:
        print(f"❌ 执行失败: {' '.join(cmd)}")
        return False


def unify_format(input_path, output_path):
    """统一视频编码格式 (H.264 + AAC)"""
    cmd = [
        "ffmpeg", "-y", "-i", input_path,
        "-c:v", "libx264", "-c:a", "aac", "-preset", "medium",
        "-movflags", "+faststart", output_path
    ]
    return run_ffmpeg(cmd, f"统一编码格式：{os.path.basename(input_path)}")


def get_video_duration(path):
    """获取视频时长（秒）"""
    cmd = [
        "ffprobe", "-v", "error", "-show_entries", "format=duration",
        "-of", "default=noprint_wrappers=1:nokey=1", path
    ]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    return float(result.stdout.strip())


def split_video(input_path, split_time, out1, out2):
    """无重编码拆分视频"""
    ok1 = run_ffmpeg(
        ["ffmpeg", "-y", "-i", input_path, "-t", str(split_time), "-c", "copy", out1],
        "拆分前半段"
    )
    ok2 = run_ffmpeg(
        ["ffmpeg", "-y", "-i", input_path, "-ss", str(split_time), "-c", "copy", out2],
        "拆分后半段"
    )
    return ok1 and ok2


def concat_videos(file_list, output):
    """用 concat 拼接视频"""
    with tempfile.NamedTemporaryFile("w", delete=False, suffix=".txt", encoding="utf-8") as tmp:
        for f in file_list:
            tmp.write(f"file '{f}'\n")
        tmp_path = tmp.name
    ok = run_ffmpeg(
        ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", tmp_path, "-c", "copy", output],
        f"拼接输出：{os.path.basename(output)}"
    )
    os.remove(tmp_path)
    return ok


def split_and_append(video_path, add_temp_path, output_folder):
    """主逻辑：统一→拆分→拼接"""
    name, _ = os.path.splitext(os.path.basename(video_path))
    unified = os.path.join(output_folder, f"{name}_unified.mp4")

    # Step 1: 统一格式
    if not unify_format(video_path, unified):
        return

    # Step 2: 获取时长并拆分
    try:
        duration = get_video_duration(unified)
    except Exception:
        print(f"❌ 无法读取时长: {video_path}")
        return
    split_time = duration / 2
    print(f"🕒 总时长 {duration:.1f}s，拆分点 {split_time:.1f}s")

    part1 = os.path.join(output_folder, f"{name}_part1.mp4")
    part2 = os.path.join(output_folder, f"{name}_part2.mp4")
    if not split_video(unified, split_time, part1, part2):
        return

    # Step 3: 拼接
    out1 = os.path.join(output_folder, f"{name}_half1_plus.mp4")
    out2 = os.path.join(output_folder, f"{name}_half2_plus.mp4")
    concat_videos([part1, add_temp_path], out1)
    concat_videos([part2, add_temp_path], out2)

    print(f"✅ 已生成两段输出：\n  ├ {out1}\n  └ {out2}\n")

    # 清理
    for f in [unified, part1, part2]:
        if os.path.exists(f):
            os.remove(f)


def main():
    x = input("📂 输入视频文件夹路径 (x): ").strip('"')
    m = input("📁 输出文件夹路径 (m): ").strip('"')
    y = input("🎞 需要追加拼接的视频路径 (y): ").strip('"')

    if not os.path.isdir(x):
        print("❌ 输入文件夹不存在")
        sys.exit(1)
    if not os.path.isfile(y):
        print("❌ 要追加的视频不存在")
        sys.exit(1)
    os.makedirs(m, exist_ok=True)

    # 统一追加视频格式
    add_temp = os.path.join(m, "_add_temp.mp4")
    print(f"⚙️ 正在统一追加视频格式...")
    if not unify_format(y, add_temp):
        print("❌ 追加视频格式转换失败")
        sys.exit(1)

    # 遍历批量处理
    for f in os.listdir(x):
        path = os.path.join(x, f)
        if not f.lower().endswith(('.mp4', '.mov', '.avi', '.mkv', '.ts')):
            continue
        print(f"\n🚀 处理文件：{f}")
        split_and_append(path, add_temp, m)

    # 清理
    if os.path.exists(add_temp):
        os.remove(add_temp)
    print("\n🎉 全部处理完成！")


if __name__ == "__main__":
    main()
